//
//  HREditAddressViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-12.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HREditAddressViewController.h"
#import "ActionSheet.h"
#import "HRAreaModel.h"

@interface HREditAddressViewController (){
    NSString *selectedProvincesCode;
    NSString *selectedProvincesName;
    NSString *selectedCityCode;
    NSString *selectedcityName;
    NSString *selectedCountyCode;
    NSString *selectedCountyName;
    
    ActionSheet *actionSheet;
    UIPickerView *picker;
    NSMutableArray *arrayProvinces;
    NSMutableArray *arrayCitys;
    NSMutableArray *arrayCountys;
    NSMutableDictionary *dicProvinceCitys;  //缓存 省－市
    NSMutableDictionary *dicCitycountys;    //缓存 市－区
}

@end

@implementation HREditAddressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        arrayProvinces = [[NSMutableArray alloc] init];
        arrayCitys = [[NSMutableArray alloc] init];
        arrayCountys = [[NSMutableArray alloc] init];
        dicProvinceCitys = [[NSMutableDictionary alloc] init];
        dicCitycountys = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (__CUR_IOS_VERSION >= __IPHONE_7_0)
    {
        self.edgesForExtendedLayout= UIRectEdgeNone;
    }
    self.navigationItem.title = @"编辑收货地址";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(editAddress)];
    [self.navigationItem setRightBarButtonItem:rightItem];
    
    [self configViews];
}

-(void)configViews{
    _txtFeildName.text = [NSString stringWithFormat:@"%@",_info.consignee ];
    _txtFeildPhone.text = [NSString stringWithFormat:@"%@",_info.phone ];
    _txtFeildCode.text = [NSString stringWithFormat:@"%@",_info.zipcode ];
    _lblArea.text = [NSString stringWithFormat:@"%@%@%@",_info.provinceName,_info.cityName,_info.sectionName];
    _txtFeildAddress2.text = @"";
    _txtFeildAddress3.text = [NSString stringWithFormat:@"%@",_info.addressDetail];
    
    selectedProvincesCode = _info.provinceCode;
    selectedProvincesName = _info.provinceName;
    selectedcityName = _info.cityName;
    selectedCityCode = _info.cityCode;
    selectedCountyCode = _info.sectionCode;
    selectedCountyName = _info.sectionName;
    
    picker = [[UIPickerView alloc] init];
    picker.delegate = self;
    picker.dataSource = self;
    actionSheet = [[ActionSheet alloc] initWithTitle:@"选择省、市、区" delegate:self cancelButtonTitle:@"确定" viewCustom:picker otherButtonTitles: nil];

}

#pragma mark -textFeild
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)actionDel:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确定删除该收货地址?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

#pragma mark -选择区域
- (IBAction)actionChooseArea:(id)sender {
    //隐藏键盘
    [self.txtFeildName resignFirstResponder];
    [self.txtFeildPhone resignFirstResponder];
    [self.txtFeildCode resignFirstResponder];
    [self.txtFeildAddress2 resignFirstResponder];
    [self.txtFeildAddress3 resignFirstResponder];
    
    //判断省份数据是否下载
    if (arrayProvinces.count== 0) {
        [self showLoadingHud:kLoading];
        [HRInterfaceManager getProvinceList:^(BOOL isSucceed, NSString *message, id data) {
            [self hideLoadingHud];
            if (isSucceed) {
                [arrayProvinces addObjectsFromArray:data];
                [picker reloadComponent:0];
                if (arrayProvinces.count) {
                    HRAreaModel *model = (HRAreaModel*)[arrayProvinces objectAtIndex:0];
                    [self updataPickcitys:model.code];
                }
                [actionSheet show];
                
            }else{
                [self showTextHUD:message];
            }
        }];
    }else{
        [actionSheet show];
    }

}

#pragma mark - 编辑
-(void)editAddress{
    if (_txtFeildName.text.length == 0) {
        [self showTextHUD:@"请输入收货人名字"];
        return;
    }
    if (_txtFeildPhone.text.length == 0) {
        [self showTextHUD:@"请输入收货人手机号码"];
        return;
    }
    
    if (![_txtFeildPhone.text checkMobileNum]) {
        [self showTextHUD:@"请输入正确的手机号码"];
        return;
    }
    if (_txtFeildAddress3.text.length == 0) {
        [self showTextHUD:@"请输入详细地址"];
        return;
    }
    [self showLoadingHud:kLoading];
    [HRInterfaceManager updateReceiveAddress:_txtFeildName.text receiveAddressId:_info.receiveAddressId phone:_txtFeildPhone.text telephone:@"" zipcode:_txtFeildCode.text email:@"" provinceCode:selectedProvincesCode provinceName:selectedProvincesName cityCode:selectedCityCode cityName:selectedcityName sectionCode:selectedCountyCode sectionName:selectedCountyName addressDetail:_txtFeildAddress3.text addressShort:@"" completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideLoadingHud];
        
        if (isSucceed) {
            if (_addressChange) {
                _addressChange();
            }
            
            [self showSuccessHud:@"更新地址成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [self showTextHUD:message];
        }
    }];
    

}

-(void)updataPickcitys:(NSString*)code{
    if ([dicProvinceCitys objectForKey:code]) {
        [arrayCitys removeAllObjects];
        [arrayCitys addObjectsFromArray:[dicProvinceCitys objectForKey:code]];
        [picker reloadComponent:1];
    }else{
        [actionSheet startLoading:kLoading];
        [HRInterfaceManager getCityList:code completion:^(BOOL isSucceed, NSString *message, id data) {
            if (isSucceed) {
                NSMutableArray *array = [[NSMutableArray alloc] init];
                if ([data isKindOfClass:[NSArray class]]) {
                    [array addObjectsFromArray:data];
                }
                [arrayCitys removeAllObjects];
                [arrayCitys addObjectsFromArray:array];
                [dicProvinceCitys setObject:array forKey:code]; //huan c
                [picker reloadComponent:1];
                
                if (arrayCitys.count) {
                    HRAreaModel *model = (HRAreaModel*)[arrayCitys objectAtIndex:0];
                    [self updatePickCountys:model.code];
                }
                
            }
            [actionSheet stopLoading];
        }];
    }
}

-(void)updatePickCountys:(NSString*)code{
    if ([dicCitycountys objectForKey:code]) {
        [arrayCountys removeAllObjects];
        [arrayCountys addObjectsFromArray:[dicCitycountys objectForKey:code]];
        [picker reloadComponent:2];
    }else{
        [actionSheet startLoading:kLoading];
        [HRInterfaceManager getCountyList:code completion:^(BOOL isSucceed, NSString *message, id data) {
            if (isSucceed) {
                NSMutableArray *array = [[NSMutableArray alloc] init];
                if ([data isKindOfClass:[NSArray class]]) {
                    [array addObjectsFromArray:data];
                    [dicCitycountys setObject:array forKey:code];
                    [arrayCountys removeAllObjects];
                    [arrayCountys addObjectsFromArray:array];
                    [picker reloadComponent:2];
                }
            }
            [actionSheet stopLoading];
        }];
    }
    
}

#pragma mark -pickerViewDelegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return arrayProvinces.count;
            break;
        case 1:
            return arrayCitys.count;
        case 2:
            return arrayCountys.count;
        default:
            break;
    }
    return 0;
}

-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (component) {
        case 0:{
            HRAreaModel *model = [arrayProvinces objectAtIndex:row];
            return model.name;
        }
        case 1:{
            HRAreaModel *model = [arrayCitys objectAtIndex:row];
            return model.name;
        }
        case 2:{
            HRAreaModel *model = [arrayCountys objectAtIndex:row];
            return model.name;
            
        }
        default:
            break;
    }
    return nil;
}

-(void)pickerView:(UIPickerView *)_pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    switch (component) {
        case 0:{  //选择省份
            HRAreaModel *model = (HRAreaModel*)[arrayProvinces objectAtIndex:row];
            [self updataPickcitys:model.code];
        }
            break;
        case 1:{  //选择城市
            HRAreaModel *model = (HRAreaModel*)[arrayCitys objectAtIndex:row];
            [self updatePickCountys:model.code];
        }
            break;
        case 2:{
        }
            break;
        default:
            break;
    }
    
}

#pragma mark -actionSheetDelegate
- (void)actionSheet:(ActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == -1) {
        HRAreaModel *pmodel = [arrayProvinces objectAtIndex:[picker selectedRowInComponent:0]];
        selectedProvincesName = [NSString stringWithFormat:@"%@",pmodel.name];
        selectedProvincesCode = [NSString stringWithFormat:@"%@",pmodel.code];
        
        HRAreaModel *cmodel = [arrayCitys objectAtIndex:[picker selectedRowInComponent:1]];
        selectedcityName = [NSString stringWithFormat:@"%@",cmodel.name];
        selectedCityCode = [NSString stringWithFormat:@"%@",cmodel.code];
        
        HRAreaModel *tmodel = [arrayCountys objectAtIndex:[picker selectedRowInComponent:2]];
        selectedCountyName = [NSString stringWithFormat:@"%@",tmodel.name];
        selectedCountyCode = [NSString stringWithFormat:@"%@",tmodel.code];
        
        _lblArea.text = [NSString stringWithFormat:@"%@ %@ %@ ",selectedProvincesName,selectedcityName,selectedCountyName];
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self showLoadingHud:kLoading];
        [HRInterfaceManager deleteReceiveAddressById:_info.receiveAddressId completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideLoadingHud];
            if (isSucceed) {
                if (_addressChange) {
                    _addressChange();
                }
                
                [self showSuccessHud:@"地址删除成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else{
                [self showTextHUD:message];
            }
        }];
    }
}


@end
